package de.reichelt.fxrequi;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Formatter;
import java.util.logging.LogRecord;

public class MyLogFormatter extends Formatter {
  
  private static final String LINE_SEPARATOR = System.getProperty("line.separator");
  private static final SimpleDateFormat fmt = new SimpleDateFormat("HH:mm:ss");
  
  @Override
  public String format(LogRecord record) {
    StringBuilder sb = new StringBuilder();

    sb.append(fmt.format(new Date(record.getMillis())))
      .append(" ["+record.getLevel().getName()+"] ")
      .append(baseName(record.getSourceClassName())+".")
      .append(record.getSourceMethodName()+"() ## ")
      .append(formatMessage(record))
      .append(LINE_SEPARATOR);

    if (record.getThrown() != null) {
      try {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        record.getThrown().printStackTrace(pw);
        pw.close();
        sb.append(sw.toString());
      } catch (Exception ex) {
        // ignore
      }
    }

    return sb.toString();
  }
  
  private String baseName(String className) {
    String[] parts = className.split("\\.");
    return parts[parts.length-1];
  }

}
